package com.chcit.mobile.mvp.inventory.fragment.move;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.chcit.custom.view.loader.QuickLoader;
import com.xuexiang.xui.widget.spinner.editspinner.EditSpinner;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.di.component.DaggerInventoryDetailComponent;
import com.chcit.mobile.di.module.InventoryDetailModule;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.entity.Locator;
import com.chcit.mobile.mvp.inventory.contract.InventoryDetailContract;
import com.chcit.mobile.mvp.entity.InventoryBean;
import com.chcit.mobile.mvp.inventory.presenter.InventoryDetailPresenter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.toast.XToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class InventoryDetailFragment extends ScanFragment<InventoryDetailPresenter> implements InventoryDetailContract.View {

    @BindView(R.id.buttom_bar_group)
    LinearLayout buttomBarGroup;
    @BindView(R.id.tv_move_detail_index)
    TextView tvIndex;
    @BindView(R.id.tv_move_detail_productName)
    TextView tvProductName;
    @BindView(R.id.tv_move_detail_productSpec)
    TextView tvProductSpec;
    /*@BindView(R.id.tv_move_detail_productionDate)
    TextView tvProductionDate;*/
    @BindView(R.id.tv_move_detail_productCode)
    TextView tvProductCode;
    @BindView(R.id.tv_move_detail_uom)
    TextView tvUom;
    @BindView(R.id.tv_move_detail_lot)
    TextView tvLot;
    @BindView(R.id.tv_move_detail_guaranteeDate)
    TextView tvGuaranteeDate;
    @BindView(R.id.tv_move_detail_manufacturer)
    TextView tvManufacturer;
    @BindView(R.id.tv_move_detail_vendor)
    TextView tvVendor;
    @BindView(R.id.tv_move_detail_movement_qty)
    TextView tvMovementQty;
    @BindView(R.id.tv_move_detail_locator)
    EditSpinner tvLocator;
    @BindView(R.id.et_move_detail_movement_number)
    AppCompatEditText etMovementNumber;
    @BindView(R.id.spinner_move_detail_to_storage_status)
    AppCompatTextView tvStorageStatusName;
    @BindView(R.id.spinner_move_detail_to_locator_name)
    EditSpinner spinnerToLocatorName;
    @BindView(R.id.bt_move_detail_cancel)
    Button btCancel;
    @BindView(R.id.bt_move_detail_ok)
    Button btOk;
    @BindView(R.id.ll_movenent_number)
    LinearLayout showLocatorNumber;
    @BindView(R.id.ll_inventory_locator)
    LinearLayout llLocator;
    MenuTypeEnum type;
    private InventoryBean storageBean = null;
    private Locator locator; //货位
    private List<Locator> locators;

    public static InventoryDetailFragment newInstance(InventoryBean storageBean,MenuTypeEnum type) {
        InventoryDetailFragment fragment = new InventoryDetailFragment();
        fragment.storageBean = storageBean;
        fragment.type = type;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerInventoryDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .inventoryDetailModule(new InventoryDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_inventory_detail, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initShowData();
        if(type == MenuTypeEnum.INVENTORY_QUERY) {
            buttomBarGroup.setVisibility(View.INVISIBLE);
            spinnerToLocatorName.setVisibility(View.GONE);
            showLocatorNumber.setVisibility(View.INVISIBLE);
            llLocator.setVisibility(View.INVISIBLE);
        }else{
            initSpinner();
        }
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
         XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
      int position = locators.indexOf(new Locator(barcodeData));
        if(position != -1 ){
            spinnerToLocatorName.setText(barcodeData);
            locator = locators.get(position);

        }else{
            JSONObject params = new JSONObject();
            params.put("value",barcodeData);
            mPresenter.getLocators(params,list->{
                locator = list.get(0);
                locators.add(locator);
                spinnerToLocatorName.setItemData(locators);
                spinnerToLocatorName.setText(barcodeData);
            });
        }
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);

        initEvent();
    }


    private void initShowData() {
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l -> {
            pop();

        });

        tvIndex.setText(storageBean.getProductName());
        tvProductName.setText(storageBean.getProductName());
        tvProductSpec.setText(storageBean.getProductSpec());
        tvManufacturer.setText(storageBean.getManufacturer());
        tvProductCode.setText(storageBean.getProductCode());
        tvUom.setText(storageBean.getUomName());
        tvLot.setText(storageBean.getLot());
        tvGuaranteeDate.setText(storageBean.getGuaranteeDate());
        tvVendor.setText(storageBean.getVendorName());
        tvMovementQty.setText((storageBean.getQtyOnHand() + ""));
        tvLocator.setText(storageBean.getLocatorName());
        etMovementNumber.setText(storageBean.getQtyOnHand() + "");
        tvStorageStatusName.setText(storageBean.getStorageStatusName());
        /* etInvoiceNo.setText(storageBean.getTaxInvoiceNo());*/

    }

    private void initSpinner() {

        locators = new ArrayList<>();//Arrays.asList("默认货位","理货货位","中药货位");

            spinnerToLocatorName.setItemData(locators);
            spinnerToLocatorName.setImageOnClickListener(new View.OnClickListener() {
                int i =0;
                @Override
                public void onClick(View v) {
                   if(i==0){
                       i++;
                       JSONObject data = new JSONObject();
                       data.put("productId", storageBean.getProductId());
                       data.put("showStorageLoc", "Y");//在库货位
                       mPresenter.getLocators(data, list -> {
                           if(list.contains(locator)){
                               locators =list;
                           }else{
                               locators.addAll(list);
                           }
                           spinnerToLocatorName.setItemData(locators);
                           locator = locators.get(0);
//                           spinnerToLocatorName.getAdapter().notifyDataSetChanged();

                       });
                   }
                }
            });


    }
    private void initEvent() {
        etMovementNumber.addTextChangedListener(new TextWatcher() {
            String beforeText;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeText = s.toString();
            }


            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String data = s.toString();

                try {
                    int number;
                    if (data.isEmpty()) {
                       number = 0;
                    } else {
                        number = Integer.parseInt(data);
                    }

                    if ((number-storageBean.getQtyOnHand().intValue()) > 0) {
                        DialogUtil.showErrorDialog(getContext(),  "移库数量必须小于等于可移数量！");
                        etMovementNumber.setText(beforeText);
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });
        etMovementNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (etMovementNumber != null) {
                        if (etMovementNumber.getText() == null || etMovementNumber.getText().toString().isEmpty()) {
                            etMovementNumber.setText("0");
                        }
                    }

                }
            }
        });
    }

    @OnClick({R.id.bt_move_detail_cancel, R.id.bt_move_detail_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_move_detail_cancel:
                pop();
                break;
            case R.id.bt_move_detail_ok:
                  /* asiID:1069000
        locatorFromID:1014717
        locatorToID:1014717
        storageStatus:S
        storageStatusTo:S
        uomQty:70
        uomBaseQty:30
        description:
        appSessionID:1541725608377.6*/
                if (spinnerToLocatorName.getText().isEmpty()) {
                    DialogUtil.showErrorDialog(getContext(),  "请输入货位！");
                    return;
                }
                JSONObject data = new JSONObject();
                data.put("locatorIdTo", locator.getLocatorId());//
                data.put("attributeSetInstanceId", storageBean.getAttributeSetInstanceId());
                data.put("qty", etMovementNumber.getText().toString());
                data.put("locatorId", storageBean.getLocatorId());
                data.put("storageStatus", storageBean.getStorageStatus());
              //  data.put("asiID",storageBean.getM_AttributeSetInstance_ID());
                mPresenter.moven(data,()->{
                    showMessage("移库成功!");
                    setFragmentResult(RESULT_OK,null);
                    pop();
                });
                break;
        }
    }

}
